<?php
class TPiece extends SQLite3
{

	public function __construct()   {
		if(file_exists(PATH_BDD.'.db')) {
			$this->open(PATH_BDD.'.db');
		}
	}

	public static function getPieces() {
		$db = new TPiece();
		$a_result = $db->query("SELECT P.ID_PIECE,DATE,MAX(ID_TEMP),VALEUR_TEMP,P.NOM_PIECE From TEMP AS T JOIN PIECE AS P ON T.ID_PIECE=P.ID_PIECE GROUP BY P.ID_PIECE");

		$a_pieces = array();
		if(!empty($a_result)) {
			while($res = $a_result->fetchArray(SQLITE3_ASSOC)) {
                                $a_pieces[] = $res;
                        }
		}
		if(!empty($a_pieces)) {
			$json = array("status" => 0, "msg" => "Chargement des pieces ok","pieces" => $a_pieces);
                        echo $_GET['jsoncallback'] . '(' . json_encode($json) . ');';
                }
                else {
                        $json = array("status" => 1, "msg" => "Aucune piece");
                        echo $_GET['jsoncallback'] . '(' . json_encode($json) . ');';
                }
                $db->close();
	}

	public static function getTemperatures($byRoom = false) {

		$db = new TPiece();
		if($byRoom)$a_result = $db->query("SELECT * From TEMP AS T JOIN PIECE AS P ON T.ID_PIECE=P.ID_PIECE GROUP BY ID_PIECE");
		else $a_result = $db->query("SELECT VALEUR_TEMP as currentTemperature,DATE From TEMP Order by ID_TEMP DESC LIMIT 1");

		$a_temperatures = array();
		if(!empty($a_result)) {
			while($res = $a_result->fetchArray(SQLITE3_ASSOC)) {
				$a_temperatures[] = $res;
			}
		}
		if(!empty($a_temperatures) && is_array($a_temperatures)) {                     		
			$json = array("status" => 0, "msg" => "Chargement des tempatures ok","temperatures" => $a_temperatures);
			echo $_GET['jsoncallback'] . '(' . json_encode($json) . ');';
		}
		else {
			$json = array("status" => 1, "msg" => "Aucune temperature");
			echo $_GET['jsoncallback'] . '(' . json_encode($json) . ');';
		}
		$db->close();
	}
}
?>
